import router from "@/router";
import nProgress from "nprogress";
import "nprogress/nprogress.css";
import store from "@/store";
import { asyncRoutes } from "@/router";

const whiteList = ['/login', '/404'] // 不需要登录的白名单
/**
 * 前置路由守卫
 * 
 * **/
router.beforeEach(async (to, from, next) => {
  nProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next({ path: '/' }) // 有token 不能访问登录页，next中有参数的话，并不会执行路由后置守卫
      nProgress.done()
    } else {
      //判断是否需要获取用户信息
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        const filterRoutes = asyncRoutes.filter(item => {
          return roles.menus.includes(item.name)
        }) //筛选后的路由
        store.commit('user/setRoutes', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }]) //添加动态路由信息到路由表
        // router添加动态路由之后需要转发一下
        next(to.path) // 转发路由，解决刷新页面后，路由表丢失的问题        
      } else {
        next() // 放行
      }


    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      nProgress.done()
    }
  }
})

/**
 * 后置路由守卫
 *  
 * **/
router.afterEach(() => {
  nProgress.done()
})